package com.summerbird.mallchat.common.common.event.listener;

import com.summerbird.mallchat.common.common.event.UserOfflineEvent;
import com.summerbird.mallchat.common.common.event.UserOnlineEvent;
import com.summerbird.mallchat.common.user.dao.UserDao;
import com.summerbird.mallchat.common.user.domain.entity.User;
import com.summerbird.mallchat.common.user.domain.enums.UserActiveStatusEnum;
import com.summerbird.mallchat.common.user.service.cache.UserCache;
import com.summerbird.mallchat.common.websocket.service.WebSocketService;
import com.summerbird.mallchat.common.websocket.service.adapter.WebSocketAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import java.util.Date;

@Component
public class UserOfflineListener {

    @Autowired
    private UserDao userDao;
    @Autowired
    private UserCache userCache;
    @Autowired
    private WebSocketService webSocketService;

    @Async
    @TransactionalEventListener(classes = UserOfflineEvent.class, phase = TransactionPhase.AFTER_COMMIT, fallbackExecution = true)
    public void saveDB(UserOfflineEvent event){
        User user = event.getUser();
        User update = new User();
        update.setId(user.getId());
        update.setLastOptTime(new Date());
        update.setActiveStatus(UserActiveStatusEnum.OFFLINE.getStatus());
        userDao.updateById(update);
    }

    @Async
    @EventListener(classes = UserOnlineEvent.class)
    public void saveRedisAndPush(UserOnlineEvent event){
        User user = event.getUser();
        userCache.offline(user.getId(), user.getLastOptTime());
        //推送给所有在线用户，该用户下线
        webSocketService.sendToAllOnline(WebSocketAdapter.buildOfflineNotifyResp(event.getUser()), event.getUser().getId());
    }

}
